package edu.intprog.egreeting;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import edu.intprog.configuration.ConfigurationManager;
import edu.intprog.sql.SessionManager;
import edu.intprog.egreeting.basic.EgreetingBaseServlet;
import edu.intprog.egreeting.beans.Greeting;
import edu.intprog.egreeting.beans.Messages;
import edu.intprog.egreeting.beans.UserDef;

/**
 * Servlet implementation class for Servlet: TemplateCustomizerServlet
 *
 */
 public class TemplateCustomizerServlet extends EgreetingBaseServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public TemplateCustomizerServlet() {
		super();
	}   	 	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if( request.getSession().getAttribute("user")==null)
		{
			//simple security measure
			getServletContext().getRequestDispatcher("/StartServlet").forward(request, response);
			return;
		}
		String selectedTitle = (String) request.getParameter("selectedTitle");
		Greeting template = getGreetingFromDB(selectedTitle);
		
		if (template!=null) 
		{
			//add the greeting required data into the request
			ConfigurationManager.fillRequestWithGreetingEssentials(request);
			
			request.setAttribute("destTarget", "_parent");
			
			//update the greeting fields that are related to the current user
			UserDef user = (UserDef) request.getSession().getAttribute("user");
			template.set_senderEmail(user.get_emailAddr());
			template.set_senderName(user.get_fName() + " " + user.get_lName());
			if (template.get_title().equals("Custom"))
				template.set_title("");
			request.setAttribute("greetingTemplate", template);
			getServletContext().getRequestDispatcher("/greetingTemplate.jsp").forward(request, response);
		}
	}
	
	/**
	 * getGreetingFromDB
	 * 
	 * run a JDBC query that fetch a greeting from the DB by it's title
	 * 
	 * @param greetingTitle - the greeting title to fetch
	 * 
	 * @return requested greeting
	 */
	private static synchronized Greeting getGreetingFromDB(String greetingTitle)
	{
		Greeting greeting = new Greeting();
		Connection conn = null;
		String userName = "egreeting";
		String password = "burgul";
		String schemeName = "egreeting";
		String url = "jdbc:mysql://localhost/" + schemeName + "?user="
		+ userName
		+ "&password="
		+ password;

		try {
			Class.forName ("com.mysql.jdbc.Driver").newInstance ();
			conn = DriverManager.getConnection (url);
			Statement s = conn.createStatement ();
			s.executeQuery ("SELECT * FROM GREETING_TEMPLATES WHERE TITLE='"+ greetingTitle +"'");
			ResultSet rs = s.getResultSet ();
			while (rs.next ())
			{
				 greeting.set_title(rs.getString ("TITLE"));
				 greeting.set_backgroundImage(rs.getString ("BACK_IMAGE"));
				 greeting.set_backgroundSound(rs.getString ("BACK_SOUND"));
				 greeting.set_personalBlessing(rs.getString ("PERSONAL_BLESSING"));
				 greeting.set_blessing(rs.getString ("BLESSING"));
				 greeting.set_greetingImage(rs.getString ("FORE_IMAGE"));
			}
			rs.close ();
			s.close ();
		} catch (Exception e) {
			greeting = null;
		}
		finally {
			if (conn != null)
			{
				try
				{
					conn.close ();
				}
				catch (Exception e) { /* ignore close errors */ }
			}
		}

		return greeting;
	}
 }